package com.action;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.dao.OrderDao;
import com.dao.RoomDao;
import com.form.Cart;
import com.form.QueryForm;
import com.model.Order;
import com.model.Orderdetail;
import com.model.Room;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 有关订单的操作类
 * 
 * @author 0912652
 */
public class OrderAction extends ActionSupport implements ModelDriven<Order> {
	private Order order = new Order();

	public Order getModel() {
		return order;
	}

	public String submitOrder() {
		//初始化各个变量
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		String id = request.getParameter("id");
		Cart cart = session.getAttribute("cart") == null ? new Cart()
				: (Cart) session.getAttribute("cart");
		List<QueryForm> forms = cart.getForms();
		Set<Integer> set = new HashSet<Integer>();

		Orderdetail orderdetail = new Orderdetail();
		List<Orderdetail> orderdetails = Collections.emptyList();
		float amount = 0;
		float zero = 0;
		RoomDao roomDao = new RoomDao();
		
		for (QueryForm queryForm : forms) {
			//统计房间数
			int rid = queryForm.getId();
			set.add(rid);
			
			Room room = roomDao.findRoomById(rid);
			// 计算价格
			float price = room.getRoomtype().getSpace();
			Calendar come = Calendar.getInstance();
			Calendar leave = Calendar.getInstance();
			come.setTime(queryForm.getBegin());
			leave.setTime(queryForm.getEnd());
			int count = leave.compareTo(come);
			amount = amount + price * count;
		}
		order.setRnum(set.size());
		order.setAmount(amount);
		order.setPamount(zero);
		
		//自动生成账单号
		Date date = new Date();
		// 定义格式为"时间+0+工号"/"时间+1+客户id"，不显示毫秒
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		String str = df.format(date);
		//支持客户网上订房的扩展功能，因此增加0/1识别位
		String oid = str + "0" + id;
		order.setPnum(oid);
		
		orderdetail.setOrder(order);
		for (QueryForm queryForm : forms) {
			Room room = roomDao.findRoomById(queryForm.getId());
			orderdetail.setCtime(queryForm.getBegin());
			orderdetail.setLtime(queryForm.getEnd());
			orderdetail.setRoom(room);
			
			orderdetails.add(orderdetail);
		}
		
		OrderDao orderDao = new OrderDao();
		order = orderDao.saveOrder(orderdetails, order);
		
		return "";
	}

}
